exports.getRecord = async (context) => {
    const cloud = context.cloud;
    const { openId } = context
    const { record_type, activity_id, env } = context.data

    if (!record_type || !activity_id || !env) {
        //校验参数
        return { success: false, data: "", message: "缺少参数record_type或activity_id或env" }
    }
    //查询记录
    try {
        const record_types = record_type.split(',')
        //查询数据库商家的session信息
        const result = await cloud.db.collection('group_by_record').find({
            activity_id,
            openId,
            record_type:{$in: record_types },
            env
        });
        if (result && result.length > 0) {
            return { success: true, data: result, message: "请求成功" };
        }
        return { success: true, data: [], message: "请求成功" }
    } catch (error) {
        return { success: false, data: [], message: "查询失败" }
    }
};

exports.insertRecord = async (context) => {
    //新增记录
    const cloud = context.cloud;
    const { openId } = context
    const { record_type, activity_id, env, isRead } = context.data
    if(typeof isRead == 'undefined') {
      return { success: false, data: "", message: "缺少参数isRead" }
    }
    if (!record_type || !activity_id || !env) {
        //校验参数
        return { success: false, data: "", message: "缺少参数record_type或activity_id或env" }
    }
    const currentTime = Date.now()
    //查询记录
    try {
        //查询数据库商家的session信息
        const queryResult = await cloud.db.collection('group_by_record').find({
            record_type,
            activity_id,
            openId,
            env
        });
        if(queryResult && queryResult.length > 0) {
            //如果有消息记录，则更新相关操作
            const updateResult = await cloud.db.collection('group_by_record').updateMany({
                openId,
                record_type,
                activity_id,
                env
                }, {
                    $set: {
                        isRead,
                        updateTime: currentTime,
                    } 
                });
            return { success: true, data: true, message: "操作成功" };
        } else {
            //没有消息记录，则新增
            const result = await cloud.db.collection('group_by_record').insertOne({
                openId,
                record_type,
                activity_id,
                env,
                isRead,
                updateTime: currentTime,
                createTime: currentTime
            });
            if (result) {
                return { success: true, data: true, message: "操作成功" };
            }
            return { success: false, data: false, message: "操作失败" }
        }
        
    } catch (error) {
        return { success: false, data: error, message: "操作失败" }
    }
};